import { defineStore } from 'pinia'
import {
  LoginFormData,
  LoginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user/index'
import { UserState } from './types/type'
import { constantRoute, anyRoute } from '@/router/routes'
//@ts-expect-error
import cloneDeep from 'lodash/cloneDeep'
const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: localStorage.getItem('token'),
      menuRoutes: [...constantRoute, anyRoute],
      username: '',
      avatar: '',
      //存储当前用户是否包含某一个按钮
      buttons: [],
    }
  },
  actions: {
    async userLogin(data: LoginFormData) {
      const res: LoginResponseData = await reqLogin(data)
      this.token = res.token as string
      this.username = data.username as string
      localStorage.setItem('token', this.token)
      return true
    },
    async getUserInfo() {
      const res: userInfoResponseData = await reqUserInfo()
      this.username = res.data.name as string
      this.avatar = res.data.avatar as string
      this.buttons = res.data.buttons
    },
    async userLogout() {
      await reqLogOut({ username: this.username })
      this.token = ''
      this.username = ''
      this.avatar = ''
      localStorage.removeItem('token')
      return true
    },
  },
  getters: {},
})

export default useUserStore
